package org.example.rental.web;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.rental.common.Result;
import org.example.rental.common.User;
import org.example.rental.domain.SysUser;
import org.example.rental.service.SysUserService;
import org.example.rental.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;


    @Autowired
    User user;

    @Autowired
    SysUserService sysUserService;





    // 原始方法调用前执行的内容
    // 返回值类型可以拦截控制的执行，true放行，false终止
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println("请求为:"+uri);

        String token = request.getHeader("authorization");
        if (token==null){
            returnNoLogin(response);
            return false;
        }
        Object o = redisUtil.get(token);

        if (o!=null){
            if (user.getSysUser()==null){
                String username = (String) redisUtil.get(token);
                SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", username));
                user.setSysUser(sysUser);
            }
            return true;
        }else {
            returnNoLogin(response);
            return false;
        }
    }



    /**
     * 返回未登录的错误信息
     * @param response ServletResponse
     */
    private void returnNoLogin(HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        // 设置返回401 和响应编码
        response.setStatus(401);
        response.setContentType("Application/json;charset=utf-8");
        // 构造返回响应体
        Result result = Result.fail(401,"你还未登录，请先登录",null);
        String resultString = JSONUtil.toJsonStr(result);
        outputStream.write(resultString.getBytes(StandardCharsets.UTF_8));
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
